﻿using System;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Popups;

namespace Win8StorageHelper
{
    /// <summary>
    /// A Class for File Storage Helper
    /// </summary>
    public static class StorageHelper
    {
        /// <summary>
        /// Checks if File exists in the location
        /// </summary>
        /// <param name="folder">Folder location as StorageFolder</param>
        /// <param name="fileName">filename as string</param>
        /// <returns></returns>
        public static async Task<StorageFile> GetFileIfExistsAsync(StorageFolder folder, string fileName)
        {
            try
            {
                return await folder.GetFileAsync(fileName);
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// Creates a Text file
        /// </summary>
        /// <param name="folder">Folder location as StorageFolder</param>
        /// <param name="fileName">fileName as string</param>
        /// <param name="fileContent">fileContent as string</param>
        public static async void CreateTextFileAsync(StorageFolder folder, string fileName, string fileContent)
        {
            StorageFile file = await folder.CreateFileAsync(fileName);
            await FileIO.WriteTextAsync(file, fileContent);
        }

        /// <summary>
        /// Reads A Text file
        /// </summary>
        /// <param name="folder">Folder location as StorageFolder</param>
        /// <param name="fileName">fileName as string</param>
        /// <returns>Returns fileContent, and null if File doesn't exist.</returns>
        public static async Task<string> ReadTextFileAsync(StorageFolder folder, string fileName)
        {
            Task<StorageFile> task = GetFileIfExistsAsync(folder, fileName);
            StorageFile file = await task;

            if (file != null)
            {
                IAsyncOperation<string> ao = FileIO.ReadTextAsync(file);
                string text = await ao;
                return text;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// Saves an image in Pictures Library
        /// </summary>
        /// <param name="imageUrl">Image Url as string</param>
        public static async void SaveImageInPicturesLibrary(string imageUrl)
        {
            if (!string.IsNullOrEmpty(imageUrl))
            {
                var client = new HttpClient();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, imageUrl);
                var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

                var filename = imageUrl.Substring(imageUrl.LastIndexOf('/') + 1);

                Task<StorageFile> task = StorageHelper.GetFileIfExistsAsync(KnownFolders.PicturesLibrary, filename);
                StorageFile file = await task;

                if (file == null)
                {
                    var imageFile = await KnownFolders.PicturesLibrary.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
                    var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
                    var writer = new DataWriter(fs.GetOutputStreamAt(0));
                    writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
                    await writer.StoreAsync();
                    writer.DetachStream();
                    await fs.FlushAsync();

                    var dialog = new MessageDialog(string.Format("The image is successfully saved in \"Pictures Library\". File name: {0}", filename), "Saving Image");
                    await dialog.ShowAsync();
                }
                else
                {
                    var dialog = new MessageDialog(string.Format("The image is already saved in \"Pictures Library\". File name: {0}", filename), "Saving Image");
                    await dialog.ShowAsync();
                }
            }
        }
    }
}
